//
//  XMMeetBoxView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/5/27.
//

#import "XMMeetBoxView.h"
#import "XMMeetBoxCell.h"

@interface XMMeetBoxView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tbl;

@property (nonatomic, strong) UIView *noDataView;
@property (nonatomic, strong) UIView *footView;

@property (nonatomic, strong) UIButton *manageBtn;
@property (nonatomic, strong) UIButton *settleBtn;
@property (nonatomic, strong) UILabel *totalPriceLabel;
@property (nonatomic, strong) UIButton *clearBtn;
@property (nonatomic, strong) UIButton *allSelectBtn;

@property (nonatomic, strong) NSArray *boxModelArr;

@property (nonatomic, strong) NSMutableArray *sectionSelectArr;
@property (nonatomic, strong) NSMutableDictionary *rowSelectDic;

@end

@implementation XMMeetBoxView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navView.backgroundColor = kColorHEX(0xF7F7F7);
    UIButton *manageBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(14.0) frame:CGRectMake(self.width - KScaleWidth(10.0) - KScaleWidth(70.0), kNavagationBarH - 44 + (44 - KScaleWidth(34.0))/2, KScaleWidth(70.0), KScaleWidth(34.0)) title:@"管理" titleColor:kColorHEX(0x000000)];
    [manageBtn setTitle:@"完成" forState:UIControlStateSelected];
    manageBtn.backgroundColor = kColorHEX(0xffffff);
    [manageBtn setCornerRadius:manageBtn.height/2];
    [manageBtn addTarget:self action:@selector(manageAction:) forControlEvents:UIControlEventTouchUpInside];
    _manageBtn = manageBtn;
    [self.navView addSubview:manageBtn];
    [self addSubview:self.tbl];
    [self addSubview:self.footView];
    [self addSubview:self.noDataView];
    _noDataView.hidden = YES;
}

//分组选中
- (void)sectionSelectAction:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        [self.sectionSelectArr addObject:@(button.tag - 20000)];
        NSMutableArray *rowArr = [self.rowSelectDic objectForKey:[NSString stringWithFormat:@"%ld", button.tag - 20000]];
        if (!rowArr) {
            rowArr = [NSMutableArray array];
        }
        XMMeetBoxModel *boxModel = self.boxModelArr[button.tag - 20000];
        for (int i = 0; i < boxModel.serviceVos.count; i ++) {
            if (![rowArr containsObject:[NSString stringWithFormat:@"%d", i]]) {
                [rowArr addObject:[NSString stringWithFormat:@"%d", i]];
            }
        }
        [self.rowSelectDic safe_setObject:rowArr forKey:[NSString stringWithFormat:@"%ld", button.tag - 20000]];;
    }
    else {
        _allSelectBtn.selected = NO;
        if ([self.sectionSelectArr containsObject:@(button.tag - 20000)]) {
            [self.sectionSelectArr removeObject:@(button.tag - 20000)];
            [self.rowSelectDic removeObjectForKey:[NSString stringWithFormat:@"%ld", button.tag - 20000]];
        }
    }
    [_tbl reloadData];
    [self priceCount];
}

//管理
- (void)manageAction:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        _totalPriceLabel.hidden = YES;
        _settleBtn.selected = YES;
        _clearBtn.hidden = NO;
    }
    else {
        _totalPriceLabel.hidden = NO;
        _settleBtn.selected = NO;
        _clearBtn.hidden = YES;
    }
}

//去首页看看
- (void)goHomeAction:(UIButton *)button {
    if (self.delegate && [self.delegate respondsToSelector:@selector(goHomeAction)]) {
        [self.delegate goHomeAction];
    }
}

//全选
- (void)selectAllAction:(UIButton *)button {
    button.selected = !button.selected;
    [self.sectionSelectArr removeAllObjects];
    [self.rowSelectDic removeAllObjects];
    if (button.selected) {
        for (int i = 0; i < self.boxModelArr.count; i ++) {
            NSMutableArray *rows = [NSMutableArray array];
            XMMeetBoxModel *boxModel = self.boxModelArr[i];
            for (int j = 0; j < boxModel.serviceVos.count; j ++) {
                [rows addObject:[NSString stringWithFormat:@"%d", j]];
            }
            [self.rowSelectDic safe_setObject:rows forKey:[NSString stringWithFormat:@"%d", i]];
        }
    }
    [_tbl reloadData];
    [self priceCount];
}

//清理失效
- (void)clearAction:(UIButton *)button {
    NSString *cartIds = @"";
    for (int i = 0; i < _boxModelArr.count; i ++) {
        XMMeetBoxModel *boxModel = _boxModelArr[i];
        for (XMServiceVosModel *serviceModel in boxModel.serviceVos) {
            if ([serviceModel.status isEqualToString:@"0"]) {
                if (cartIds.length > 0) {
                    cartIds = [cartIds stringByAppendingFormat:@",%@", serviceModel.cartId];
                }
                else {
                    cartIds = serviceModel.cartId;
                }
            }
        }
    }
    if (cartIds.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(meetDeleteWithCartIds:)]) {
            [self.delegate meetDeleteWithCartIds:cartIds];
        }
    }
    else {
        [MBProgressHUD showError:@"暂无失效见面"];
    }
}

//结算
- (void)settleAction:(UIButton *)button {
    if (self.rowSelectDic.count == 0) {
        [MBProgressHUD showError:@"请选择要结算的见面"];
        return;
    }
    NSString *cartIds = @"";
    NSArray *keys = [self.rowSelectDic allKeys];
    NSMutableArray *selectServiceModelArr = [NSMutableArray array];
    for (int i = 0; i < keys.count; i ++) {
        NSString *keyStr = keys[i];
        NSArray *rowArr = [self.rowSelectDic safeArrayForKey:keyStr];
        XMMeetBoxModel *boxModel = self.boxModelArr[[keyStr integerValue]];
        for (NSString *rowStr in rowArr) {
            XMServiceVosModel *serviceModel = boxModel.serviceVos[[rowStr integerValue]];
            if (cartIds.length > 0) {
                cartIds = [cartIds stringByAppendingFormat:@",%@", serviceModel.cartId];
            }
            else {
                cartIds = serviceModel.cartId;
            }
            [selectServiceModelArr addObject:serviceModel];
        }
    }
    if (_manageBtn.selected) { //删除见面
        if (self.delegate && [self.delegate respondsToSelector:@selector(meetDeleteWithCartIds:)]) {
            [self.delegate meetDeleteWithCartIds:cartIds];
        }
    }
    else {   //结算见面
        if (self.delegate && [self.delegate respondsToSelector:@selector(settleWithSelectServiceModelArr:selectRowDic:)]) {
            [self.delegate settleWithSelectServiceModelArr:self.boxModelArr
                                              selectRowDic:self.rowSelectDic];
        }
    }
}

//加载接口数据
- (void)setContentWithBoxModelArr:(NSArray *)boxModelArr {
    _tbl.hidden = boxModelArr.count == 0;
    _noDataView.hidden = boxModelArr.count > 0;
    self.navTitleLabel.text = [NSString stringWithFormat:@"见面箱（%ld）", boxModelArr.count];
    self.boxModelArr = boxModelArr;
    [self priceCount];
    [_tbl reloadData];
//    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"合计：¥%@", @"46.8"] attributes:@{NSFontAttributeName : KBoldFontSize(27.0), NSForegroundColorAttributeName : kColorHEX(0xFF0000)}];
//    [attr addAttributes:@{NSFontAttributeName : KFontSize(13.0), NSForegroundColorAttributeName : kColorHEX(0x000000)} range:NSMakeRange(0, 3)];
//    [attr addAttributes:@{NSFontAttributeName : KFontSize(12.0), NSForegroundColorAttributeName : kColorHEX(0xFF0000)} range:NSMakeRange(3, 1)];
//    [_totalPriceLabel setAttributedText:attr];
}

//计算价格
- (void)priceCount {
    CGFloat price = 0;
    if (self.rowSelectDic.count > 0) {
        NSArray *keys = [self.rowSelectDic allKeys];
        for (int i = 0; i < keys.count; i ++) {
            NSString *keyStr = keys[i];
            NSArray *selectRows = [self.rowSelectDic safeArrayForKey:keyStr];
            for (NSString *rowStr in selectRows) {
                XMMeetBoxModel *boxModel = self.boxModelArr[[keyStr integerValue]];
                XMServiceVosModel *serviceModel = boxModel.serviceVos[[rowStr integerValue]];
                price += [serviceModel.price floatValue];
            }
        }
    }
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"合计：¥%.2f", price] attributes:@{NSFontAttributeName : KBoldFontSize(27.0), NSForegroundColorAttributeName : kColorHEX(0xFF0000)}];
    [attr addAttributes:@{NSFontAttributeName : KFontSize(13.0), NSForegroundColorAttributeName : kColorHEX(0x000000)} range:NSMakeRange(0, 3)];
    [attr addAttributes:@{NSFontAttributeName : KFontSize(12.0), NSForegroundColorAttributeName : kColorHEX(0xFF0000)} range:NSMakeRange(3, 1)];
    [_totalPriceLabel setAttributedText:attr];
}

#pragma mark - Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.boxModelArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    XMMeetBoxModel *meetBoxModel = _boxModelArr[section];
    return meetBoxModel.serviceVos.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return KScaleWidth(62.0) + KScaleWidth(10.0);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, KScaleWidth(62.0) + KScaleWidth(10.0))];
    headView.backgroundColor = kColorHEX(0xffffff);
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, headView.width, KScaleWidth(10.0))];
    topView.backgroundColor = kColorHEX(0xF7F7F7);
    [headView addSubview:topView];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, headView.height - 1, headView.width, 1)];
    lineView.backgroundColor = kColorHEX(0xF1F1F1);
    [headView addSubview:lineView];
    
    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(KScaleWidth(5.0), topView.maxY + (KScaleWidth(62.0) - KScaleWidth(28.0))/2, KScaleWidth(28.0), KScaleWidth(28.0)) image:@"mine_select_icon" selectImg:@"mine_select_icon_select"];
    [selectBtn addTarget:self action:@selector(sectionSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    selectBtn.tag = 20000 + section;
    [headView addSubview:selectBtn];
    if (self.allSelectBtn.selected) {
        selectBtn.selected = YES;
    }
    if ([self.sectionSelectArr containsObject:@(section)]) {
        selectBtn.selected = YES;
    }
    XMMeetBoxModel *boxModel = _boxModelArr[section];
    UIImageView *avatarImgView = [[UIImageView alloc] initWithFrame:CGRectMake(KScaleWidth(35.0), KScaleWidth(10.0) + (headView.height - KScaleWidth(10.0) - KScaleWidth(28.0))/2, KScaleWidth(28.0), KScaleWidth(28.0))];
    avatarImgView.contentMode = UIViewContentModeScaleAspectFit;
    [avatarImgView sd_setImageWithURL:[NSURL URLWithString:boxModel.avatar] placeholderImage:ImageNamed(@"mine_avatar_icon")];
//    avatarImgView.image = [UIImage imageWithColor:kColorHEX(0x00ffff)];
    [avatarImgView setCornerRadius:avatarImgView.height/2];
    [headView addSubview:avatarImgView];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(73.0), KScaleWidth(10.0), headView.width - KScaleWidth(73.0), headView.height - KScaleWidth(10.0)) font:KFontSize(15.0) textColor:kColorHEX(0x1E1C1C)];
    nameLabel.text = boxModel.nickname;//@"不懂得董小姐";
    [headView addSubview:nameLabel];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScaleWidth(105.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMMeetBoxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMMeetBoxCellName"];
    NSString *currentIndex = [NSString stringWithFormat:@"%ld", indexPath.row];
    XMMeetBoxModel *boxModel = _boxModelArr[indexPath.section];
    XMServiceVosModel *serviceModel = boxModel.serviceVos[indexPath.row];
    if (self.allSelectBtn.selected) {
        [cell setContentWithBoxModel:serviceModel select:YES];
    }
    else if ([self.sectionSelectArr containsObject:@(indexPath.section)]) {
        [cell setContentWithBoxModel:serviceModel select:YES];
    }
    else {
        NSMutableArray *rowArr = [self.rowSelectDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.section]];
        [cell setContentWithBoxModel:serviceModel select:[rowArr containsObject:currentIndex]];
    }
    XMWeakSelf;
    cell.itemSelectBlock = ^(BOOL selected) {
        NSMutableArray *rowArr = [weakSelf.rowSelectDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.section]];
        if (!rowArr) {
            rowArr = [NSMutableArray array];
        }
        if (selected) {
            [rowArr addObject:currentIndex];
            [weakSelf.rowSelectDic safe_setObject:rowArr forKey:[NSString stringWithFormat:@"%ld", indexPath.section]];
            [tableView reloadData];
        }
        else {
            weakSelf.allSelectBtn.selected = NO;
            if ([weakSelf.sectionSelectArr containsObject:@(indexPath.section)]) {
                [weakSelf.sectionSelectArr removeObject:@(indexPath.section)];
            }
            if ([rowArr containsObject:currentIndex]) {
                [rowArr removeObject:currentIndex];
                [weakSelf.rowSelectDic safe_setObject:rowArr forKey:[NSString stringWithFormat:@"%ld", indexPath.section]];
                [tableView reloadData];
            }
        }
        [tableView reloadData];
        [self priceCount];
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Init
- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - kNavagationBarH - kBottomLayout - KScaleWidth(78.0))];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        _tbl.separatorInset = UIEdgeInsetsMake(0, KScaleWidth(35.0), 0, 0);
        _tbl.separatorColor = kColorHEX(0xF1F1F1);
        _tbl.backgroundColor = kColorHEX(0xF7F7F7);
        [_tbl registerClass:[XMMeetBoxCell class] forCellReuseIdentifier:@"XMMeetBoxCellName"];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
    }
    return _tbl;
}

- (UIView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - KScaleWidth(78.0) - kBottomLayout - kNavagationBarH)];
        _noDataView.backgroundColor = kColorHEX(0xF7F7F7);
        
        UIImageView *noDataImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + _noDataView.height/2 - KScaleWidth(140.0) - KScaleWidth(44.0), self.width, KScaleWidth(140.0))];
        noDataImgView.contentMode = UIViewContentModeScaleAspectFit;
        noDataImgView.image = ImageNamed(@"mine_meetbox_nodata_icon");
        [_noDataView addSubview:noDataImgView];
        
        UIButton *goHomeBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KBoldFontSize(17.0) frame:CGRectMake((_noDataView.width - KScaleWidth(230.0))/2, noDataImgView.maxY + KScaleWidth(24.0), KScaleWidth(230.0), KScaleWidth(44.0)) title:@"去首页看看吧" titleColor:kColorHEX(0x333333)];
        [goHomeBtn setGradientLayerWithLocations:@[@(0), @(1.0)] colors:@[(__bridge id)kColorHEX(0xFFD800).CGColor, (__bridge id)kColorHEX(0xFFE44E).CGColor] startPoint:CGPointMake(0.5, 0.37) endPoint:CGPointMake(0.03, 0.37)];
        [goHomeBtn setCornerRadius:goHomeBtn.height/2];
        [goHomeBtn addTarget:self action:@selector(goHomeAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataView addSubview:goHomeBtn];
    }
    return _noDataView;
}

- (UIView *)footView {
    if (!_footView) {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - kBottomLayout - KScaleWidth(78.0), self.width, kBottomLayout + KScaleWidth(78.0))];
        _footView.backgroundColor = kColorHEX(0xffffff);
        [_footView setShadowOffset:CGSizeMake(0, 2) shadowOpacity:1 shadowRadius:9 shadowColor:kColorHEXA(0x000000, 0.25)];
        
        UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(KScaleWidth(5.0), KScaleWidth(25.0), KScaleWidth(66.0), KScaleWidth(28.0)) image:@"mine_select_icon" selectImg:@"mine_select_icon_select"];
        [selectBtn setTitle:@"全选" forState:UIControlStateNormal];
        [selectBtn setTitleColor:kColorHEX(0x676767) forState:UIControlStateNormal];
        [selectBtn addTarget:self action:@selector(selectAllAction:) forControlEvents:UIControlEventTouchUpInside];
        [selectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, KScaleWidth(7.0), 0, 0)];
        [_footView addSubview:selectBtn];
        _allSelectBtn = selectBtn;
        
        [_footView addSubview:self.settleBtn];
        [_footView addSubview:self.clearBtn];
        _clearBtn.hidden = YES;
        [_footView addSubview:self.totalPriceLabel];
    }
    return _footView;
}

- (UIButton *)settleBtn {
    if (!_settleBtn) {
        _settleBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(15.0) frame:CGRectMake(self.width - KScaleWidth(15.0) - KScaleWidth(100.0), (KScaleWidth(78.0) - KScaleWidth(46.0))/2, KScaleWidth(100.0), KScaleWidth(46.0)) title:@"结算" titleColor:kColorHEX(0x333333)];
        [_settleBtn setTitle:@"删除" forState:UIControlStateSelected];
        [_settleBtn setBackgroundImage:[UIImage gradientColorImageFromColors:@[kColorHEX(0xFFE44E), kColorHEX(0xFFD800)] gradientType:GradientTypeLeftToRight imgSize:_settleBtn.frame.size] forState:UIControlStateNormal];
        [_settleBtn addTarget:self action:@selector(settleAction:) forControlEvents:UIControlEventTouchUpInside];
        [_settleBtn setCornerRadius:_settleBtn.height/2];
    }
    return _settleBtn;
}

- (UIButton *)clearBtn {
    if (!_clearBtn) {
        _clearBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(15.0) frame:CGRectMake(self.width - KScaleWidth(126.0) - KScaleWidth(100.0), self.settleBtn.y, KScaleWidth(100.0), KScaleWidth(48.0)) title:@"清理失效" titleColor:kColorHEX(0xffffff)];
        _clearBtn.backgroundColor = kColorHEX(0xDEDEDE);
        [_clearBtn setCornerRadius:_clearBtn.height/2];
        [_clearBtn addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearBtn;
}

- (UILabel *)totalPriceLabel {
    if (!_totalPriceLabel) {
        _totalPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(70.0), 0, self.width - KScaleWidth(70.0) - KScaleWidth(123.0), KScaleWidth(78.0))];
        _totalPriceLabel.textAlignment = NSTextAlignmentRight;
    }
    return _totalPriceLabel;
}

- (NSMutableArray *)sectionSelectArr {
    if (!_sectionSelectArr) {
        _sectionSelectArr = [NSMutableArray array];
    }
    return _sectionSelectArr;
}

- (NSMutableDictionary *)rowSelectDic {
    if (!_rowSelectDic) {
        _rowSelectDic = [NSMutableDictionary dictionary];
    }
    return _rowSelectDic;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
